package com.trip.service;

import com.trip.dao.tables.pojos.AdminDomain;
import com.trip.dao.tables.records.AdminRecord;
import com.trip.exception.ServiceException;
import com.trip.util.StringUtil;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.trip.dao.Tables.ADMIN;

/**
 * Created by hc24 on 2017/12/24.
 */
@Service
public class AdminService {

    @Autowired
    private DSLContext dslContext;

    public AdminDomain login(String loginName,String password,String ip){
        String enPassword= StringUtil.md5(password).substring(0,30);
        AdminRecord record= dslContext.selectFrom(ADMIN).where(ADMIN.LOGIN_NAME.eq(loginName),ADMIN.PASSWORD.eq(enPassword)).fetchOne();

        if(record==null)
            throw new ServiceException("Login fail: unknown login name or bad password");
        record.setLatestLoginIp(ip);
        record.setLatestLoginTime(LocalDateTime.now());

        AdminDomain domain=record.into(AdminDomain.class);
        domain.setPassword(null);

        return domain;
    }

}
